#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "server.h"

QVector<QTcpSocket*> clientlist;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //创建QTcpServer
    myserver=new QTcpServer(nullptr);//父对象为空
    myserver->listen(QHostAddress::Any,10000);//对象用. 指针用->
    //接受连接
    connect(myserver, &QTcpServer::newConnection, this, [=](){//这里等到下一个连接的时候会释放上一个连接
            //阻塞等待客户端发起请求
            //获得QTcpSocket
            QTcpSocket *sockettemp = myserver->nextPendingConnection();
            //m_tcp->push_back(sockettemp);
            seed++;
            server *serverthread=new server(seed,sockettemp);//这里不能用实体，只能指针，会覆盖
            clientlist.push_back(sockettemp);
            qDebug()<<"成功和客户端建立了新的连接...";
            serverthread->start();
            connect(serverthread,&server::getmsg,this,[=](QString recvMsg){
                QByteArray byteArray = recvMsg.toUtf8();
                for(auto it=clientlist.begin();it!=clientlist.end();++it){
                    (*it)->write(byteArray);
                    (*it)->waitForBytesWritten();
                    qDebug()<<"成功发送："<<recvMsg;
                }
            });
            });
//    connect(serverthread,&server::getmsg,this,[=](QString recvMsg){
//        QByteArray byteArray = recvMsg.toUtf8();
//        for(auto it=clientlist.begin();it!=clientlist.end();++it){
//            (*it)->write(byteArray);
//            (*it)->waitForBytesWritten();
//            qDebug()<<"成功发送："<<recvMsg;
//        }
//        });
}

MainWindow::~MainWindow()
{
    delete ui;
}

